/** \file    SquareCreate.cpp
  * \brief   Creates segmentation, dividing masked region on squares of given size.
  * \date    2002
  * \author  Fedor Chelnokov
  * \version $Header: /home/cscom1r4/cvsroot/cs/segm/src/SquareCreate.cpp,v 1.1 2004/05/20 09:11:46 cscom1r4 Exp $
  */

#include "typelib/types.h"

#include "imglib/bitmap.h"
#include "imglib/segmbasic.h"
#include "imglib/colorate.h"
#include "imglib/imageclass.h"

#include "segm/Segmentation.h"

///segment checker for mask and square frequency as sources
class square_checker
{
public:
	square_checker(const img::bitmap &mask, size_t size, size_t offset) : 
		_mask(mask), _size(size), _offset(size-offset) {}

	bool top(size_t x, size_t y) const
		{ return _mask(x,y-1) == _mask(x,y) && (_mask(x,y) == false || sq(x,y-1) == sq(x,y)); }
	bool left(size_t x, size_t y) const
		{ return _mask(x-1,y) == _mask(x,y) && (_mask(x,y) == false || sq(x-1,y) == sq(x,y)); }
	bool top_left(size_t x, size_t y) const
		{ return _mask(x-1,y-1) == _mask(x,y) && (_mask(x,y) == false || sq(x-1,y-1) == sq(x,y)); }
	bool top_right(size_t x, size_t y) const
		{ return _mask(x+1,y-1) == _mask(x,y) && (_mask(x,y) == false || sq(x+1,y-1) == sq(x,y)); }

private:
	//returns owner square of a pixel
	size_point sq(size_t x, size_t y) const {
		return size_point((x + _offset) / _size, (y + _offset) / _size);
	}

private:
	const img::bitmap &_mask;
	size_t _size;
	size_t _offset;
};

void Segmentation::squareCreate(const img::bitmap &mask, 
	size_t size, size_t offset, const byte_image *colorateImg)
{
	index_map imap(mask.width(), mask.height());
	img::relabel(imap, square_checker(mask, size, offset));

	segm_image& segm = reinterpret_cast<segm_image&>(imap);
	if (colorateImg)
		img::colorate(*colorateImg, imap, segm, img::BGRA<size_t>());

	index_map::iterator ii(imap.begin());
	for (; ii != imap.end(); ++ii)
		if (!mask[ii])
			*ii = 0; //black color for outmask region

	create(segm);
	mergeSmall(size*size/5, size*size);
}
